<template>
  <uni-popup ref="spec" type="bottom" :maskClick="true" @touchmove="" class="popup">
    <view class="wrap">
      <view class="flex justify-between">
        <view class="margin-right">
          <image class="block-150 radius bg-gray" mode="aspectFill" :src="info.thumb" @click="preview(info.thumb)"></image>
        </view>
        <view class="flex-sub flex flex-direction justify-between">
          <view class="text-cut-2">{{info.name}}</view>
          <view class="text-sm text-theme">
            <text class="text-price">{{minPrice}}</text>
            <text class="margin-lr-xs">-</text>
            <text class="text-price">{{maxPrice}}</text>
          </view>
        </view>
        <view class="close-box">
          <text class="cuIcon-close" @tap="close"></text>
        </view>
      </view>
      <scroll-view class="content" scroll-y>
        <view>
          <block v-for="(item,index) in sku_list" :key="index">
            <view class="content-item solid-bottom">
              <view class="left">
                <view class="text-df text-333 text-cut key_name">{{item.key_name}}</view>
                <view class="text-xs text-999 text-theme margin-top-xs">
                  <text class="text-price">{{item.curPrice || item.shop_price}}</text>
                </view>
              </view>
              <view class="right">
                <view>
                  <uni-number-box :value="item.number" :min="0" :max="item.stock" @change="changeNumber($event,index)"
                    :step="1">
                  </uni-number-box>
                </view>
                <view class="text-xs text-999 margin-top-xs">{{i18n['库存']}}: {{item.stock}}</view>
              </view>
            </view>
          </block>
        </view>
      </scroll-view>
      <view class="flex justify-between align-center margin-top" v-if="sku_list.length == 0">
        <text>{{i18n['数量']}}:</text>
        <uni-number-box :value="info.number" :max="info.stock" @change="changeNoSpecNumber($event)" :step="1"></uni-number-box>
      </view>
      <view class="flex justify-end align-center text-sm margin-top">
        <text>{{i18n['共']}}<text class="text-theme">{{buyInfo.total}}</text></text>
        <text class="text-price text-theme margin-left">{{buyInfo.price}}</text>
      </view>
      <view class="margin-top flex round overHidden">
        <view v-if="type == 'all' || type == 'cart'" class="flex-sub btn color1" @tap.stop="handleAddCart">
          {{i18n['加购物车']}}
        </view>
        <view v-if="type == 'all' || type == 'buy'" class="flex-sub btn color2" @tap.stop="handleBuyNow">
          {{i18n['立即订购']}}
        </view>
      </view>
    </view>
  </uni-popup>
</template>

<script>
  import uniNumberBox from '../uni-number-box/uni-number-box.vue';
  export default {
    components: {
      uniNumberBox,
    },
    props: {
      // spu规格列表
      speclist: {
        type: Array,
        default () {
          return []
        }
      },
      // sku列表
      skulist: {
        type: Array,
        default () {
          return []
        }
      },
      //
      currentId: {
        type: [String, Number],
        default: 0,
      },
      //
      info: {
        type: Object,
      },
      //判断要处理的数据来源  1 代表来着 积分兑换
      dataSource: {
        type: [String, Number],
        default: 0,
      },
      //
      limit: {
        type: Number,
        default: 0,
      },
      //
      isCart: {
        type: Boolean,
        default: false,
      },
      // 最低价
      minPrice: {
        type: [String, Number],
        default: 0,
      },
      // 最高价
      maxPrice: {
        type: [String, Number],
        default: 0,
      },
    },
    data() {
      return {
        /**
         * 加入类型
         * 点击加购物车打开弹窗,只展示加购物车按钮 (type: cart)
         * 点击立即购买打开痰喘,只展示立即购买按钮 (type: buy)
         * 点击规格栏目打开弹窗,两个按钮都展示 (type: all)
         * */
        type: 'all', // 按钮展示模式
        shopItemInfo: {}, // 匹配字典
        selectArr: [], // 选中的id
        selectArrVal: [], // 选中的值
        selectIndex: [], // 选中的index
        selectShop: {}, // 选中的商品
        number: 1, // 选择数量
        stock: 0,
        min: 0,
        max: 99,
        selectAll: {},
        sku_list: [], // sku列表
        buyInfo: {
          total: 0,
          price: 0,
        }, // 计算数量,价格
        is_wholesale: true,
      };
    },
    watch: {
      info(val) {
        if (this.limit == 0) {
          this.max = val.stock;
        } else {
          this.max = this.limit > val.stock ? val.stock : this.limit;
        }
        this.stock = val.stock;
      },
      limit(val) {
        if (val) {
          this.max = val;
        }
      },
      speclist(newVal) {
        // console.log('newVal',newVal);
        if (newVal.length != 0) {

        }
      },
      skulist(newVal) {
        if (newVal.length != 0) {
          this.sku_list = newVal.map(item => {
            item.number = 0;
            return item;
          });
        }
      },
    },
    methods: {
      // 规格预览图片
      preview(urls) {
        uni.previewImage({
          current: urls,
          urls: [urls]
        })
      },
      // 初始化规格
      init() {
        this.selectArr = []; // 选中的id
        this.selectArrVal = []; // 选中的值
        this.selectIndex = []; // 选中的index
        this.selectShop = {}; // 选中的商品
        this.shopItemInfo = {}; // 匹配字典
        this.speclist.forEach(item => {
          this.selectArr.push('');
          this.selectArrVal.push('');
          this.selectIndex.push(-1);
        });
        this.checkItem(); // 计算sku里面的规格形成路径
        this.checkInpath(-1); // 检查生成的路径
        this.autoClickSku(); // 自动选择sku策略
      },
      // 计算有多少种可选路径
      checkItem() {
        let result = this.skulist.reduce(
          (arrs, items) => {
            return arrs.concat(
              items.sku_spec.reduce(
                (arr, item) => {
                  return arr.concat(
                    arr.map((item2) => {
                      // 结果去重
                      if (!this.shopItemInfo.hasOwnProperty([...item2, item]) && items.stock != 0) {
                        this.shopItemInfo[[...item2, item]] = items;
                      }
                      return [...item2, item];
                    })
                  );
                },
                [
                  []
                ]
              )
            );
          },
          [
            []
          ]
        );
      },
      // 循环所有属性判断哪些属性可选
      // 当前选中的兄弟节点和已选中属性不需要循环
      checkInpath(clickIndex) {
        for (let i = 0, len = this.speclist.length; i < len; i++) {
          if (i == clickIndex) {
            continue;
          }
          let len2 = this.speclist[i].spec_value.length;
          for (let j = 0; j < len2; j++) {
            if (this.selectIndex[i] != -1 && this.selectIndex[i] == j) {
              continue;
            }
            let choose_copy = [...this.selectArr];
            this.$set(choose_copy, i, this.speclist[i].spec_value[j].id);
            let choose_copy2 = choose_copy.filter(item => item !== "" && typeof item != "undefined");
            if (this.shopItemInfo.hasOwnProperty(choose_copy2)) {
              // console.log('允许选择', this.speclist[i].spec_value[j]);
              this.$set(this.speclist[i].spec_value[j], "disabled", false);
            } else {
              // console.log('不允许选择', this.speclist[i].spec_value[j]);
              this.$set(this.speclist[i].spec_value[j], "disabled", true);
            }
          }
        }
      },
      // 选择规格
      selectSpec(item, index, $event, index2) {
        if (item.disabled) return;
        if (this.selectArr[index] != item.id) {
          this.$set(this.selectArr, index, item.id);
          this.$set(this.selectArrVal, index, item.item);
          this.$set(this.selectIndex, index, index2);
        } else {
          this.$set(this.selectArr, index, "");
          this.$set(this.selectArrVal, index, "");
          this.$set(this.selectIndex, index, -1);
        }
        this.checkInpath(index);
        // 如果全部选完
        this.checkSelectShop();
      },
      // 检测是否已经选择完sku
      checkSelectShop() {
        if (this.selectArr.every(item => item != '')) {
          this.selectShop = this.shopItemInfo[this.selectArr];
          this.setStock(this.shopItemInfo[this.selectArr]);
          this.$emit('changeSpec', this.selectShop);
        } else {
          this.selectShop = {};
        }
      },
      // 检测sku选项是否已全部选完,且有库存
      checkSelectComplete() {
        return new Promise((resolve, reject) => {
          const {
            selectShop
          } = this;
          // 判断如果存在规格 is_spec =1 存在
          if (this.info.is_spec == 1) {
            if (!selectShop || !selectShop.sku_id) {

              this.$message.info(this.i18n['请先选择规格']);
              reject && reject();
            } else {
              resolve && resolve();
            }
          } else {
            resolve && resolve();
          }
        })
      },
      // 确定选择
      handleConfirmChange() {
        this.$util.debounce(() => {
          this.close();
          if (this.sku_list.length != 0) {
            let skus = this.sku_list.reduce((arr, item) => {
              if (Number(item.number)) {
                arr.push({
                  sku_id: item.sku_id,
                  number: item.number,
                });
              }
              return arr;
            }, [])
            this.$emit('buyNow', skus);
          } else {
            this.$emit('buyNow', this.info.number);
          }
        }, 800, true);
      },
      // 设置库存
      setStock(skuInfo) {
        const {
          stock
        } = skuInfo;
        this.stock = stock;
        let limit = this.limit;
        if (limit == 0) {
          this.max = stock;
        } else {
          let n = stock > limit ? limit : stock;
          this.max = n;
        }
      },
      // 自动选择sku策略
      autoClickSku() {
        let skuInfo = this.skulist.find(item => item.sku_id == this.currentId);
        if (!skuInfo || skuInfo.stock == 0) {
          skuInfo = this.skulist.find(item => item.stock > 0);
        }
        if (skuInfo) {
          let selectSpecId = skuInfo.sku_spec;
          this.speclist.forEach((item, index) => {
            if (item.spec_value.length != 0) {
              let item2 = item.spec_value.find(ele => ele.id == selectSpecId[index]);
              let index2 = item.spec_value.findIndex(ele => ele.id == selectSpecId[index]);
              this.selectSpec(item2, index, {}, index2);
            }
          })
        }
      },
      // 打开弹窗
      open(type) {
        this.type = type || 'all';
        this.$refs.spec.open();
      },
      // 关闭弹窗
      close() {
        this.$refs.spec.close();
      },
      // 加入购物车
      handleAddCart() {
        this.$util.debounce(() => {
          this.close();
          if (this.sku_list.length != 0) {
            // 有规格操作
            let skus = this.sku_list.reduce((arr, item) => {
              if (Number(item.number)) {
                arr.push({
                  sku_id: item.sku_id,
                  num: item.number,
                });
              }
              return arr;
            }, [])
            this.$emit('addCart', skus);
          } else {
            this.$emit('addCart', this.info.number);
          }
        }, 800, true);
      },
      // 立即购买
      handleBuyNow() {
        this.$util.debounce(() => {
          this.close();
          if (this.sku_list.length != 0) {
            // 有规格操作
            let skus = this.sku_list.reduce((arr, item) => {
              if (Number(item.number)) {
                arr.push({
                  sku_id: item.sku_id,
                  number: item.number,
                });
              }
              return arr;
            }, [])
            this.$emit('buyNow', skus);
          } else {
            this.$emit('buyNow', this.info.number);
          }
        }, 800, true);
      },
      // 改变数量
      changeNumber(e, index) {
        this.sku_list[index].number = e;
        let _price = this.computedCurPrice(this.sku_list[index].shop_price,this.sku_list[index].batch_data,e);
        // this.$set(this.sku_list[index],'curPrice',_price);
        this.sku_list[index].curPrice = _price;
        // 重新计算价格
        this.computePrice();
      },
      // 计算价格
      computePrice() {
        let obj = this.sku_list.reduce((info, item, list) => {
          if (Number(item.number)) {
            let arr = JSON.parse(JSON.stringify(item.batch_data)).reverse();
            let whole = arr.find(ele => Number(ele.start_batch) <= Number(item.number));
            if (whole) {
              info.price += Number(item.number) * Number(whole.trade_price);
            } else {
              info.price += Number(item.number) * Number(item.shop_price);
            }
            info.total += Number(item.number);
          }
          info.price = Math.round(info.price*100)/100;
          return info;
        }, {
          total: 0,
          price: 0
        });
        this.buyInfo = obj;
      },
      // 无规格计算
      changeNoSpecNumber(e) {
        this.info.number = e;
        let arr = JSON.parse(JSON.stringify(this.info.batch_data)).reverse();
        let whole = arr.find(ele => Number(ele.start_batch) <= Number(e));
        let price = 0;
        if (whole) {
          price = Number(e) * Number(whole.trade_price);
        } else {
          price = Number(e) * Number(this.info.shop_price);
        }
        price = Math.round(price*100)/100;
        this.buyInfo = {
          total: e,
          price: price,
        };
      },
      // 计算当前数量所使用的的价格
      computedCurPrice(shop_price,batch_data,num){
        let arr = JSON.parse(JSON.stringify(batch_data)).reverse();
        let whole = arr.find(ele => Number(ele.start_batch) <= Number(num));
        let price = 0;
        if (whole) {
          return Number(whole.trade_price).toFixed(2);
        } else {
          return Number(shop_price).toFixed(2);
        }
      },
    }
  }
</script>

<style lang="scss" scoped>
  .wrap {
    padding-bottom: 0;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);

    .close-box {
      width: 40rpx;
      height: 40rpx;
      border-radius: 50%;
      background-color: rgba(0, 0, 0, .1);
      display: flex;
      align-items: center;
      justify-content: center;
      color: #999999;
      font-size: 28rpx;
      font-weight: bold;
    }

    .content {
      height: auto;
      max-height: 650rpx;

      .content-item {
        display: flex;
        justify-content: space-between;
        height: 120rpx;

        .left {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          width: 70%;
        }

        .right {
          // min-width: ;
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          justify-content: center;
        }
      }
    }

    .item {
      display: flex;
      flex-wrap: wrap;

      .item-tag {
        display: inline-block;
        font-size: 24rpx;
        color: #333;
        background-color: #F5F5F5;
        padding: 12rpx 24rpx;
        border-radius: 100rpx;
        margin-right: 20rpx;
        margin-bottom: 20rpx;
        border: 2rpx solid #F5F5F5;
      }

      .item-tag.active {
        background-color: #FFF2EF;
        color: $theme;
        border-color: $theme;
      }

      .item-tag.disable {
        color: #CCCCCC !important;
      }
    }

    .btn {
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      color: #FFFFFF;
    }
  }

  .block-150 {
    width: 150rpx;
    height: 150rpx;
    min-width: 150rpx;
    min-height: 150rpx;
  }

  .color1 {
    background-color: #343434;
  }

  .color2 {
    background: $bgtheme;
  }

  .overHidden {
    overflow: hidden;
  }

  .popup /deep/.uni-popup__wrapper-box {
    max-height: 100% !important;
  }
</style>
